package zjut.raymond.witdemo.ui;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blakequ.bluetooth_manager_lib.scan.BluetoothScanManager;
import com.blakequ.bluetooth_manager_lib.scan.ScanOverListener;
import com.blakequ.bluetooth_manager_lib.scan.bluetoothcompat.ScanCallbackCompat;
import com.blakequ.bluetooth_manager_lib.scan.bluetoothcompat.ScanResultCompat;

import java.util.ArrayList;
import java.util.List;

import zjut.raymond.witdemo.R;
import zjut.raymond.witdemo.ui.adapter.MyAdapter;
import zjut.raymond.witdemo.viewmodel.MyViewModel;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment implements View.OnClickListener {
    private RecyclerView recyclerView;
    private Button btnScan, btnConnect;
    private ArrayList<String> deviceMacs;
    private ArrayList<String> deviceList; // 数据源 ： 所有扫描到的设备mac地址
    private MyAdapter adapter;
    public static final String TAG = "HomeFragment";
    private int GPS_REQUEST_CODE = 10;
    private String selectDeviceMac = null;

    private MyViewModel myViewModel;
    private BluetoothScanManager scanManager;

    public HomeFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Inflate the layout for this fragment
        myViewModel = new ViewModelProvider(getActivity()).get(MyViewModel.class);
        recyclerView = getView().findViewById(R.id.ry_ble_list);
        btnScan = getView().findViewById(R.id.btn_scan);
        btnConnect = getView().findViewById(R.id.btn_link);
        btnScan.setOnClickListener(this);
        btnConnect.setOnClickListener(this);
        deviceMacs = new ArrayList<>();
        deviceList = new ArrayList<>();

        adapter = new MyAdapter(getContext(), deviceList);
        adapter.setOnItemLister(new MyAdapter.OnItemListener() {
            @Override
            public void onClick(View v, int pos, String projectc) {
                adapter.setDefSelect(pos);
                Log.d(TAG, "onClick: " + projectc);
                selectDeviceMac = projectc.split(",")[1];
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);
        initBle();
        requestPermission();
        //   adapter.notifyDataSetChanged();
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (getContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
            if (getContext().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
            }
        }
    }

    private void initBle() {
        scanManager = BluetoothScanManager.getInstance(getContext());
        scanManager.setScanOverListener(new ScanOverListener() {
            @Override
            public void onScanOver() {

            }
        });
        scanManager.setScanCallbackCompat(new ScanCallbackCompat() {
            @Override
            public void onScanResult(int callbackType, ScanResultCompat result) {
                super.onScanResult(callbackType, result);
                String strName = result.getLeDevice().getName();
                if (strName == null) return;
                //    if (strName.contains("WT")) {
                String strMAC = result.getLeDevice().getAddress();
                int iRssi = result.getLeDevice().getRssi();
                String strdevice = String.format("%s,%s,%ddb", strName, strMAC, iRssi);
                if (!deviceMacs.contains(strMAC)) {
                    deviceMacs.add(strMAC);
                    deviceList.add(strdevice);
                    adapter.notifyDataSetChanged();
                } else {
                    int iIndex = deviceMacs.indexOf(strMAC);
                    deviceList.remove(iIndex);
                    deviceList.add(iIndex, strdevice);
                    adapter.notifyDataSetChanged();
                }
                //    }
            }

            @Override
            public void onBatchScanResults(List<ScanResultCompat> results) {
                super.onBatchScanResults(results);
            }

            @Override
            public void onScanFailed(int errorCode) {
                super.onScanFailed(errorCode);
                Log.i("lc", "onScanFailed" + errorCode);
                if (errorCode == SCAN_FAILED_LOCATION_CLOSE) {
                    Toast.makeText(getContext(), "Location is closed, you should open first", Toast.LENGTH_LONG).show();
                } else if (errorCode == SCAN_FAILED_LOCATION_PERMISSION_FORBID) {
                    Toast.makeText(getContext(), "You have not permission of location", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getContext(), "Other exception", Toast.LENGTH_LONG).show();
                }
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_scan:
                scanManager.startScanNow(); //立即开始扫描
//
//                POST请求（json字符串）
//                1.拿到okhttpClient对象
//                2.设置提交类型MediaType+json字符串
//                3.构造Request
//                4.创建一个Call对象
//                5.异步请求enqueue(Callback)
//                JSONObject jsonObject = new JSONObject();
//                try {
//                    jsonObject.put("accX", Math.random()*2);
//                    jsonObject.put("accY", Math.random()*2);
//                    jsonObject.put("accZ", Math.random()*10);
//                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    jsonObject.put("updateTime", format.format(new Date()));
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
////                http://47.101.186.100:9102/sensor/add
//                OkHttpUtil.sendPostOkHttpRequest("http://47.101.186.100:9102/sensor/add", jsonObject.toString(), new Callback() {
//                    @Override
//                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
//                        e.printStackTrace();
//                        Log.d(TAG, "onFailure: ");
//                    }
//
//                    @Override
//                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//                        Log.d(TAG, "onResponse: " + response.body().string());
//                    }
//                });

                break;
            case R.id.btn_link:
                if (selectDeviceMac != null) {
                    myViewModel.setDeviceMac(selectDeviceMac);
                    NavController controller = Navigation.findNavController(v);
                    controller.navigate(R.id.action_homeFragment_to_dataFragment);
                } else {
                    Toast.makeText(getContext(),"未选择设备", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void openGPSSettings() {
        if (checkGPSIsOpen()) {
            scanManager.startScanNow(); //立即开始扫描
        } else {
            //没有打开则弹出对话框
            new AlertDialog.Builder(getContext())
                    .setTitle(R.string.notifyTitle)
                    .setMessage(R.string.gpsNotifyMsg)
                    // 拒绝, 退出应用
                    .setNegativeButton(R.string.cancel,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    getActivity().finish();
                                }
                            })

                    .setPositiveButton(R.string.setting,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //跳转GPS设置界面
                                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                    startActivityForResult(intent, GPS_REQUEST_CODE);
                                }
                            })

                    .setCancelable(false)
                    .show();
        }
    }

    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    @Override
    public void onResume() {
        super.onResume();
        openGPSSettings();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 如果正在扫描中 停止扫描
        if (scanManager.isScanning()) {
            scanManager.stopCycleScan();
        }
    }
}